package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etoak.common.core.vo.PageVO;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-06-30
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {
    @Override
    public Dishes getByName(String name) {
        return this.lambdaQuery()
                .eq(Dishes::getName, name)
                .one();
    }

    @Override
    public ResultVO add(Dishes dishes) {
        if (ObjUtil.isNotEmpty(this.getByName(dishes.getName()))) {
            return ResultVO.error("菜品名称已存在");
        }
        dishes.setCreateTime(DateUtil.now());
        if (this.save(dishes)) {
            return ResultVO.success("菜品添加成功");
        } else {
            return ResultVO.error("菜品添加失败");
        }
    }

    @Override
    public ResultVO<PageVO<DishesVO>> getList(int pageNum, int pageSize, Dishes dishes) {
        Page<DishesVO> page = new Page<>(pageNum, pageSize);
        page = this.baseMapper.getList(page,dishes);
        return ResultVO.success(PageVO.of(page.getRecords(),page.getTotal()));
    }

    @Override
    public ResultVO updateDishes(Integer id, Dishes dishes) {
        if (ObjUtil.isEmpty(this.getById(id))) {
            return ResultVO.error("菜品不存在");
        }
        if (StrUtil.isNotEmpty(dishes.getName())){
            Dishes one = getByName(dishes.getName());
            if (ObjUtil.isNotEmpty(one) && !one.getId().equals(id)) {
                return ResultVO.error("菜品名称已存在");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        if (this.updateById(dishes)) {
            return ResultVO.success("菜品更新成功");
        } else {
            return ResultVO.error("菜品更新失败");
        }
    }

    @Override
    public ResultVO deleteDishes(Integer id) {
        if (ObjUtil.isEmpty(this.getById(id))) {
            return ResultVO.error("菜品不存在");
        }
        if (this.removeById(id)) {
            return ResultVO.success("菜品删除成功");
        } else {
            return ResultVO.error("菜品删除失败");
        }
    }
}
